package util;

import com.sun.xml.internal.ws.util.StringUtils;
import constant.CrowdConstant;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class CrowdUtil {


    public static String md5(String source) {
        // 1.判断source是否有效
        if (source == null || source.length() == 0) {
            // 2.如果不是有效字符串抛出异常
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }
        // 3.获取MessageDigest对象
        try {
            String algorithm = "md5";
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);

         // 4.获取铭文字符串的字节数组
            byte[] input = source.getBytes();
         // 5. 执行加密
            byte[] output = messageDigest.digest(input);
         // 6.创建BigInterger对象
            int sigum = 1;
            BigInteger bigInteger = new BigInteger(sigum, output);
         // 7.按照16进制将bigInteger的值转化为字符串
            int radis = 16;
            String encoded = bigInteger.toString(radis).toUpperCase();
            return encoded;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static boolean judeRequesType(HttpServletRequest request) {
        // 1 获取请求消息头
        String accepttHeader = request.getHeader("Accept");
        String xRequestHeader = request.getHeader("X-Requested-With");
        if ((accepttHeader != null && accepttHeader.contains("application/json")) ||
                (xRequestHeader != null && xRequestHeader.equals("XMLHttpRequest"))) {
            return true;
        }
        return false;
    }
}
